package com.glsc.ngateway.platform.controller.costallocation;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.glsc.ngateway.common.api.platform.dto.it.ServerDeviceExportFull;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.dto.cmdb.CmdbCommonDetailImportDto;
import com.glsc.ngateway.platform.domain.costallocation.BusiSystemInfo;
import com.glsc.ngateway.platform.domain.costallocation.CostAllocationTask;
import com.glsc.ngateway.platform.domain.costallocation.ReplenishmentInfo;
import com.glsc.ngateway.platform.dto.*;
import com.glsc.ngateway.platform.service.costallocation.CostAllocationTaskService;
import com.glsc.ngateway.platform.utils.ExcelUtil;
import com.glsc.ngateway.platform.utils.report.ReportUploadContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author guoj
 * @description: 数据分摊任务
 * @date 2024/10/17 10:56
 */
@RestController
@RequestMapping("/costAllocationTask")
@Api(value = "BusiSystemInfoController", tags = {"数据分摊任务"})
public class CostAllocationTaskController {
    @Autowired
    private CostAllocationTaskService costAllocationTaskService;
    @Value("${export.it}")
    public String itpath;
    @Autowired
    private HttpServletRequest request;

    @PostMapping("/listpage")
    @ApiOperation(value = "查询分页")
    public PlatformResponse<Page<CostAllocationTask>> listpage(@ApiParam(value = "查询条件") @RequestBody CostAllocationTaskQueryDto costAllocationTaskQueryDto) {
        return PlatformResponse.successData(costAllocationTaskService.findPage(costAllocationTaskQueryDto));
    }

    @PostMapping("/genCostAllocationTask")
    @ApiOperation(value = "生成分摊数据任务")
    public PlatformResponse<?> genCostAllocationTask(@ApiParam(value = "生成条件") @RequestBody CostAllocationTaskQueryDto costAllocationTaskQueryDto) {
        costAllocationTaskService.genCostAllocationTask(costAllocationTaskQueryDto);
        return PlatformResponse.successData(null);
    }

    @RequestMapping(method = RequestMethod.POST, value = "export")
    @ApiOperation(value = "根据查询条件内容导出excel", notes = "根据查询条件内容导出excel")
    public ResponseEntity<byte[]> exportServerFullOutPut(@ApiParam(value = "查询条件") @RequestBody CostAllocationTaskQueryDto costAllocationTaskQueryDto) throws Exception {

        List<CostAllocationTaskExportDto> result = costAllocationTaskService.queryExportData(costAllocationTaskQueryDto);
        List<ExcelUtil.MultipleSheelPropety> list = new ArrayList<>();

        WriteSheet sheet = EasyExcel.writerSheet(0, "分摊数据导出").build();
        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropety.setData(result);
        multipleSheelPropety.setSheet(sheet);

        list.add(multipleSheelPropety);

        String fileName = itpath + "资产分摊数据.xlsx";
        //String fileName = "D:\\guoju\\downloadfile" + "资产分摊数据.xlsx";
        ExcelUtil.writeWithMultipleSheel(fileName, list);

        String targetName = fileName;
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        //使用URLEncoder来防止文件名乱码或者读取错误
        headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode("资产分摊数据.xlsx", "utf-8"));
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

        return entity;
    }

    @PostMapping("/upload")
    @ApiOperation(value = "导入云管数据", notes = "导入云管数据")
    public PlatformResponse<?> uploadPartDetail(@RequestPart("file") MultipartFile file) throws IOException {
        ReportUploadContext<UploadReturnAmountDto, String> context = costAllocationTaskService.uploadReturnAmount(file);
        return context.isCheckPass() ? PlatformResponse.successData(context.getReadRes()) : PlatformResponse.failedMsg(String.join(",", context.getCheckRes()));
    }

    @PostMapping("/uploadSpecial")
    @ApiOperation(value = "导入云管多余数据", notes = "导入云管多余数据")
    public PlatformResponse<?> uploadPartDetailSpecial(@RequestPart("file") MultipartFile file) throws IOException {
        ReportUploadContext<UploadReturnAmountDto, String> context = costAllocationTaskService.uploadReturnAmountSpecail(file);
        return context.isCheckPass() ? PlatformResponse.successData(context.getReadRes()) : PlatformResponse.failedMsg(String.join(",", context.getCheckRes()));
    }

    @GetMapping("/getAllTaskNames")
    @ApiOperation(value = "获取全部任务名称", notes = "获取全部任务名称")
    public PlatformResponse<?> getAllTaskNames() {
        List<String> context = costAllocationTaskService.getAllTasks();
        return  PlatformResponse.successData(context);
    }


    @GetMapping("/systemListPage")
    @ApiOperation(value = "系统维度统计数据", notes = "系统维度统计数据")
    public PlatformResponse<Page<SystemStaticDto>> systemListPage(@RequestParam String taskName,
                                                                  @RequestParam(required = false) String ip,
                                                                  @RequestParam(required = false) String systemClassNo,
                                                                  @RequestParam(required = false) String pageSize,
                                                                  @RequestParam(required = false) String pageNo) {
        Page<SystemStaticDto> context = costAllocationTaskService.systemListPage(taskName,systemClassNo,ip,pageSize,pageNo);
        return  PlatformResponse.successData(context);
    }

    @GetMapping("/systemDetailListPage")
    @ApiOperation(value = "系统维度统计明细", notes = "系统维度统计明细")
    public PlatformResponse<Page<SystemDetailStaticDto>> systemDetailListPage(@RequestParam String taskName,
                                                                  @RequestParam String ip,
                                                                  @RequestParam String systemClassNo,
                                                                   @RequestParam(required = false) String pageSize,
                                                                  @RequestParam(required = false) String pageNo) {
        Page<SystemDetailStaticDto> context = costAllocationTaskService.systemDetailListPage(taskName,systemClassNo,ip,pageSize,pageNo);
        return  PlatformResponse.successData(context);
    }


    @GetMapping("/depListPage")
    @ApiOperation(value = "部门维度统计数据", notes = "部门维度统计数据")
    public PlatformResponse<Page<DepartmentStaticDto>> depListPage(@RequestParam String taskName,
                                                                  @RequestParam(required = false) String depGradeOneId,
                                                                  @RequestParam(required = false) String systemClassNo,
                                                                  @RequestParam(required = false) String pageSize,
                                                                  @RequestParam(required = false) String pageNo) {
        Page<DepartmentStaticDto> context = costAllocationTaskService.depListPage(taskName,systemClassNo,depGradeOneId,pageSize,pageNo);
        return  PlatformResponse.successData(context);
    }

    @GetMapping("/depDetailListPage")
    @ApiOperation(value = "部门维度统计明细", notes = "部门维度统计明细")
    public PlatformResponse<Page<DepartmentStaticDetailDto>> depDetailListPage(@RequestParam String taskName,
                                                                              @RequestParam String depGradeOneId,
                                                                              @RequestParam String systemClassNo,
                                                                              @RequestParam(required = false) String vcIp,
                                                                              @RequestParam(required = false) String itUniqueKey,
                                                                              @RequestParam(required = false) String pageSize,
                                                                              @RequestParam(required = false) String pageNo) {
        Page<DepartmentStaticDetailDto> context = costAllocationTaskService
                .depDetailListPage(taskName,systemClassNo,depGradeOneId,
                vcIp,itUniqueKey,pageSize,pageNo);
        return  PlatformResponse.successData(context);
    }


    @RequestMapping(method = RequestMethod.GET, value = "systemStaticExport")
    @ApiOperation(value = "成本分摊统计-系统维度内容导出excel", notes = "根据查询条件内容导出excel")
    public ResponseEntity<byte[]> exportSystem(@RequestParam String taskName,
                                               @RequestParam(required = false) String ip,
                                               @RequestParam(required = false) String systemClassNo) throws Exception {

        List<CostAllocationTaskSystemExportDto> result = costAllocationTaskService.getExportSystemStatic(taskName,systemClassNo,ip);
        List<ExcelUtil.MultipleSheelPropety> list = new ArrayList<>();

        WriteSheet sheet = EasyExcel.writerSheet(0, "成本分摊统计-系统维度数据").build();
        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropety.setData(result);
        multipleSheelPropety.setSheet(sheet);

        list.add(multipleSheelPropety);

        String fileName = itpath + "成本分摊统计-系统维度数据.xlsx";
        //String fileName = "D:\\guoju\\downloadfile" + "成本分摊统计-系统维度数据.xlsx";
        ExcelUtil.writeWithMultipleSheel(fileName, list);

        String targetName = fileName;
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        //使用URLEncoder来防止文件名乱码或者读取错误
        headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode("成本分摊统计-系统维度数据.xlsx", "utf-8"));
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

        return entity;
    }
    @RequestMapping(method = RequestMethod.GET, value = "depStaticExport")
    @ApiOperation(value = "成本分摊统计-部门维度内容导出excel", notes = "根据查询条件内容导出excel")
    public ResponseEntity<byte[]> exportDep(@RequestParam String taskName,
                                            @RequestParam(required = false) String depOneId,
                                            @RequestParam(required = false) String systemClassNo) throws Exception {

        List<CostAllocationTaskDepExportDto> result = costAllocationTaskService.getDepStaticExportData(taskName,depOneId,systemClassNo);
        List<ExcelUtil.MultipleSheelPropety> list = new ArrayList<>();

        WriteSheet sheet = EasyExcel.writerSheet(0, "成本分摊统计-部门维度数据").build();
        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropety.setData(result);
        multipleSheelPropety.setSheet(sheet);

        list.add(multipleSheelPropety);

        String fileName = itpath + "成本分摊统计-部门维度数据.xlsx";
        //String fileName = "D:\\guoju\\downloadfile" + "成本分摊统计-部门维度数据.xlsx";
        ExcelUtil.writeWithMultipleSheel(fileName, list);

        String targetName = fileName;
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        //使用URLEncoder来防止文件名乱码或者读取错误
        headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode("成本分摊统计-部门维度数据.xlsx", "utf-8"));
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

        return entity;
    }


    @RequestMapping(method = RequestMethod.POST, value = "replenishmentExport")
    @ApiOperation(value = "成本分摊统计-导出补充数据", notes = "成本分摊统计-导出补充数据")
    public ResponseEntity<byte[]> exportReplenishment(@ApiParam(value = "查询条件") @RequestBody ReplenishmentInfoQueryDto replenishmentInfo) throws Exception {

        List<ReplenishmentInfoExportDto> result = costAllocationTaskService.getReplenishmentData(replenishmentInfo);
        List<ExcelUtil.MultipleSheelPropety> list = new ArrayList<>();

        WriteSheet sheet = EasyExcel.writerSheet(0, "成本分摊统计-导出补充数据").build();
        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropety.setData(result);
        multipleSheelPropety.setSheet(sheet);

        list.add(multipleSheelPropety);

        String fileName = itpath + "成本分摊统计-导出补充数据.xlsx";
        //String fileName = "D:\\guoju\\downloadfile" + "成本分摊统计-导出补充数据.xlsx";
        ExcelUtil.writeWithMultipleSheel(fileName, list);

        String targetName = fileName;
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        //使用URLEncoder来防止文件名乱码或者读取错误
        headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode("成本分摊统计-导出补充数据.xlsx", "utf-8"));
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);

        return entity;
    }

    @PostMapping("/uploadReplenishment")
    @ApiOperation(value = "导入云管多余数据-补充数据", notes = "导入云管多余数据-补充数据")
    public PlatformResponse<?> uploadReplenishment(@RequestPart("file") MultipartFile file) throws IOException {
        ReportUploadContext<UploadReturnAmountDto, String> context = costAllocationTaskService.uploadReplenishment(file);
        return context.isCheckPass() ? PlatformResponse.successData(context.getReadRes()) : PlatformResponse.failedMsg(String.join(",", context.getCheckRes()));
    }

    @PostMapping("/listpageReplenishment")
    @ApiOperation(value = "查询补充数据分页")
    public PlatformResponse<Page<ReplenishmentInfo>> listpageReplenishment(@ApiParam(value = "查询条件") @RequestBody ReplenishmentInfoQueryDto replenishmentInfoQueryDto) {
        return PlatformResponse.successData(costAllocationTaskService.listpageReplenishment(replenishmentInfoQueryDto));
    }
}
